
const path = require('path');  // 引入 path 模块
const fs = require('fs');  // 引入 fs 模块，用于文件系统操作
/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
  const { router, controller } = app;
  // 为所有路由添加前缀/api
  router.prefix('/api')
  // 自动加载 app/router/ 目录下的所有路由文件
  const routerDir = path.join(__dirname, 'router');
  fs.readdirSync(routerDir).forEach(file => {
    if (file.endsWith('.js')) {
      const routeModule = require(path.join(routerDir, file));
      if (typeof routeModule === 'function') {
        routeModule(app); // 加载每个路由文件
      } else {
        Object.keys(routeModule).forEach(key => {
          const routes = routeModule[key];
          routes.forEach(route => {
            const method = route.method.toLowerCase();
            const path = route.path;
            const controller = route.controller;
            const middlewares = route.middlewares || [];
            if (middlewares.includes('auth')) {
              router[method](path, app.middleware.auth({ app }), controller);
            } else {
              router[method](path, controller);
            }
          });
        });
      }
    }
  });
};
